import { defineStore } from 'pinia'
 
import router from '@/router'
import {wxApi} from '@/api/index'
const { getOpenid, getToken, getWxUserInfo, getHospitalInfo } = wxApi

export const useAuthStore = defineStore('auth', {
  state: () => ({
    wxCode: '',
    wxUserInfo: null,
    openid: localStorage.getItem('openid') || null,
    token: localStorage.getItem('token') || null,
    wxAppId: import.meta.env.VITE_WX_APP_ID,  // 修改这里
    hospital: null
  }),
  
  actions: {
    async getWxAuth() {
      const redirectUri = encodeURIComponent(window.location.origin + '/doctor/login')
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.wxAppId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    },
  
    async handleWxCallback(code) {
      try {
        if (import.meta.env.MODE === 'development') {  // 修改这里
          // 开发环境下设置默认的 openid
          console.log('开发环境下设置默认的 openid');
          const mockOpenid = 'o_fngvhCIGEEJq0IBYjm1WkBNrPc';
          this.openid = mockOpenid;
          localStorage.setItem('openid', mockOpenid);
        } else {
          const { data } = await getOpenid({
            appid: this.wxAppId,
            code
          })
          this.openid = data.data
          localStorage.setItem('openid', data.data)
        }

        const tokenResponse = await getToken({providerId: 'wechat-report', openid: this.openid, type: 'wechat-report' })
        if (tokenResponse.status === 401) {
          router.push('/doctor/login')
          return false;
        }
  
        this.token = tokenResponse.data.token
        
        localStorage.setItem('token', tokenResponse.data.token)
  
        const userInfoResponse = await getWxUserInfo({ openid: this.openid, appid: this.wxAppId })
        this.wxUserInfo = userInfoResponse.data
        localStorage.setItem('wxUserInfo', JSON.stringify(userInfoResponse.data))
  
        const hospitalResponse = await getHospitalInfo({ openid: this.openid, appid: this.wxAppId })
        this.hospital = hospitalResponse.data
        localStorage.setItem('hospital', JSON.stringify(hospitalResponse.data))
  
        router.push('/doctor/list')
        return true;
      } catch (error) {
        console.error('处理微信回调出错', error)
        router.push('/doctor/login')
        return false;
      }
    }
  }
}) 